package com.pm.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.pm.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WeChatUtils {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 企业Id
     */
    @Value("${wechat.corpid}")
    private String corpid;
    /**
     * 应用私钥
     */
    @Value("${wechat.corpsecret}")
    private String corpsecret;

    /**
     * 应用ID
     * */
    @Value("${wechat.agentId}")
    private String agentId;

    /**
     * url
     */
    @Value("${wechat.url}")
    private String url;

    /**
     * 获取企业微信调用接口token
     * @return
     */
    public String getAccessToken() {
        String tokenKey=Constants.COMPANY_WECHAT_ACCESS_KEY;
        String qywxToken = (String) redisTemplate.opsForValue().get(tokenKey);
        if(StringUtils.isEmpty(qywxToken)){
            //获取token
            String accessTokenUrl= UriComponentsBuilder.fromHttpUrl(url).path(Constants.COMPANY_WECHAT_TOKEN_PATH)
            .queryParam(Constants.CORPID,corpid).queryParam(Constants.CORPSECRET,corpsecret).build().toUriString();
            JSONObject result = restTemplate.getForObject(accessTokenUrl,JSONObject.class);
            String access_token = result.getString(Constants.COMPANY_WECHAT_ACCESS_TOKEN);
            redisTemplate.opsForValue().set(tokenKey,access_token,2, TimeUnit.HOURS);
            return access_token;
        }
        return qywxToken;
    }


    /**
     * 根据电话号码获取userId
     *
     * @param token
     * @param phone
     * @return
     */
    public String getUserIdByPhone(String token, String phone) {

        JSONObject param = new JSONObject();
        param.put(Constants.MOBILE,phone);
        String userId = null;

        String path = UriComponentsBuilder.fromHttpUrl(url).path(Constants.COMPANY_WECHAT_GETUSER_PATH).queryParam(Constants.COMPANY_WECHAT_ACCESS_TOKEN,token).build().toUriString();
        ResponseEntity<JSONObject> result = restTemplate.postForEntity(path,param,JSONObject.class);
        if(result.getStatusCode().is2xxSuccessful()){
            JSONObject data = result.getBody();
            if(Constants.STRING_ZERO.equals(data.getString(Constants.ERRCODE))){
                userId = data.getString(Constants.USERID);
            }
        }

        return userId;
    }


    /**
     * 发送企业微信文字消息
     *
     * @param token
     * @param content 文本内容 消息内容，最长不超过2048个字节，超过将截断
     * @param tousers 消息接收人  最多100人
     * @return
     */
    public AjaxResult sendTextMessage(String token, String content, List<String> tousers ) {

        JSONObject param = new JSONObject();
        param.put(Constants.MSGTYPE,Constants.TEXT);
        param.put(Constants.AGENTID,agentId);
        JSONObject con = new JSONObject();
        con.put(Constants.CONTENT,content);
        param.put(Constants.TEXT,con);
        String users = tousers.stream().filter(Objects::nonNull).collect(Collectors.joining("|"));
        param.put(Constants.TOUSER,users);

        //请求链接
        String path = UriComponentsBuilder.fromHttpUrl(url).path(Constants.COMPANY_WECHAT_SENDMSG_PATH).queryParam(Constants.COMPANY_WECHAT_ACCESS_TOKEN,token).build().toUriString();
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(path,param,JSONObject.class);
        String errMsg ;
        if(responseEntity.getStatusCode().is2xxSuccessful()){
            JSONObject res = responseEntity.getBody();
            log.info("企业微信发送消息返回报文:{}",res);
            if(Constants.STRING_ZERO.equals(res.getString(Constants.ERRCODE))){
                return AjaxResult.success("消息发送成功!");
            }else{
                errMsg =  res.getString(Constants.ERRMSG);
            }
        }else{
            errMsg = "消息发送异常!";
        }

        return AjaxResult.error(errMsg);
    }
}
